#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>        // Only needed for Arduino 1.6.5 and earlier
#include "SSD1306Wire.h" // legacy: #include "SSD1306.h"
SSD1306Wire display(0x3c, 2, 14);
const char *ssid = "0_SevDaisy Mate 10";
const char *password = "66752928";
const char *mqtt_server = "47.93.197.229";
const char *client_id = "clientID_31801146";
const char *user_name = "dashboard_zyy";
const char *user_passwd = "123456";
const char *topic = "zyy_31801146";
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
void setup_wifi(){
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char *topic, byte *payload, unsigned int length){
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String str = "";
  for (int i = 0; i < length; i++){
    str += (char)payload[i];
  }
  Serial.println();
  display.clear();
  display.drawString(10, 10, topic);
  display.drawString(10, 26, str);
  display.display();
}
void reconnect(){
  while (!client.connected()){
    Serial.print("Attempting MQTT connection...");
    if (client.connect(client_id, user_name, user_passwd)){
      Serial.println("connected");
      client.publish(topic, "zyy so cute");
      client.subscribe(topic);
    }else{
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}
void setup(){
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  display.init();
  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_16);
  display.setTextAlignment(TEXT_ALIGN_LEFT);
}
void loop(){
  if (!client.connected()){
    reconnect();
  }
  client.loop();
  unsigned long now = millis();
  if (now - lastMsg > 2000){
    lastMsg = now;
    ++value;
    snprintf(msg, MSG_BUFFER_SIZE, "zyy so cute #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish(topic, msg);
  }
}